package com.galleryviewpager.l_clean;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import com.galleryviewpager.R;

public class CleanView extends View {

    private Paint mPaint;

    private int mWidth, mHeight;

    private int startX, startY, endX, endY, controlX, controlY;
    private Path mPath;
    private Bitmap mBitmap;

    private boolean isUp = true;

    public CleanView(Context context) {
        this(context, null);
    }

    public CleanView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CleanView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initPaint();
    }

    private void initPaint() {
        mPaint = new Paint();

        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(10f);

        mPath = new Path();

        mBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        mWidth = widthMode == MeasureSpec.EXACTLY ? MeasureSpec.getSize(widthMeasureSpec) : 600;
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        mHeight = heightMode == MeasureSpec.EXACTLY ? MeasureSpec.getSize(heightMeasureSpec) : 600;
        setMeasuredDimension(mWidth, mHeight);

        startX = mWidth / 5;
        endX = mWidth / 5 * 4;
        startY = endY = mHeight / 2;

        controlX = mWidth / 2;
        controlY = mHeight;


    }

    @Override
    protected void onDraw(Canvas canvas) {
        mPath.reset();
        canvas.drawColor(Color.GREEN);
        mPath.moveTo(startX, startY);
        if (controlY >= startY) {
            mPath.quadTo(controlX, controlY, endX, endY);
        } else {
            mPath.quadTo(controlX, startY, endX, endY);
        }
        mPaint.setColor(Color.YELLOW);
        canvas.drawPath(mPath, mPaint);

        mPaint.setColor(Color.RED);
        canvas.drawCircle(startX, startY, 10, mPaint);
        canvas.drawCircle(endX, endY, 10, mPaint);

        canvas.drawBitmap(mBitmap, mWidth / 2 - mBitmap.getWidth() / 2, controlY - (controlY - mHeight /2) / 2 - mBitmap.getHeight(), mPaint);

        if (isUp) {
            if (controlY > 100) {
                controlY -= 10;
            } else {
                isUp = false;
            }
        } else {
            controlY += 10;
            if (controlY >= mHeight) {
                isUp = true;
            }
        }

        postInvalidateDelayed(20);
    }
}
